package com.run.go.gearbox.mysql.handler;

import com.run.go.gearbox.mysql.MysqlTransmission;
import com.run.go.gearbox.mysql.codec.MySqlDecoder;
import com.run.go.gearbox.mysql.codec.NettyMysqlDecoder;
import com.run.go.gearbox.mysql.codec.parse.Connected;
import com.run.go.gearbox.mysql.codec.parse.Connecting;
import com.run.go.gearbox.mysql.enums.ClientCapabilities;
import com.run.go.gearbox.mysql.enums.ExtendedClientCapabilities;
import com.run.go.gearbox.mysql.enums.MysqlCharacterSet;
import com.run.go.gearbox.mysql.request.LoginCredentials;
import com.run.go.gearbox.mysql.request.LoginRequest;
import com.run.go.gearbox.mysql.response.OkResponse;
import com.run.go.gearbox.mysql.response.ServerGreeting;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.EnumSet;

public class MysqlNettyHandler extends SimpleChannelInboundHandler {

    private final Logger logger = LoggerFactory.getLogger(MysqlNettyHandler.class);

    public final String DECODER = MysqlTransmission.class.getName() + ".decoder";


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        Channel channel = channelHandlerContext.channel();
        if(o instanceof ServerGreeting){
            logger.info("TCP 握手完事 密码验证");
            ServerGreeting serverGreeting = (ServerGreeting) o;
            LoginCredentials loginWith = new LoginCredentials("root","123456","lc");
            LoginRequest loginRequest = new LoginRequest(loginWith,
                    EnumSet.of(
                            ClientCapabilities.LONG_PASSWORD,
                            ClientCapabilities.FOUND_ROWS,
                            ClientCapabilities.LONG_COLUMN_FLAG,
                            ClientCapabilities.CONNECT_WITH_DB,
                            ClientCapabilities.LOCAL_FILES,
                            ClientCapabilities.PROTOCOL_4_1,
                            ClientCapabilities.TRANSACTIONS,
                            ClientCapabilities.SECURE_AUTHENTICATION),
                    EnumSet.of(
                            ExtendedClientCapabilities.MULTI_RESULTS
                    ),
                    MysqlCharacterSet.UTF8_UNICODE_CI, serverGreeting.getSalt());
            /* 密码验证 */
            channel.writeAndFlush(loginRequest);
        }else if(o instanceof OkResponse.FinishLogin){
            logger.info("连接成功");
        }

    }

}
